import React, { useState,useEffect } from "react";
import { Button, Popover,Input,Tooltip  } from "antd";
import TimeRangeSelector from '@/components/TimeRangeSelector'; // 请改为你的实际路径
import moment, { Moment } from "moment";

export type TimeRangeDropdownValueType={
    label?:string;
    start: Date;
    end: Date;
}

interface TimeRangeDropdownProps {
  initialRange?: TimeRangeDropdownValueType;
  onChanged?: (range: TimeRangeDropdownValueType) => void;
}

const TimeRangeDropdown: React.FC<TimeRangeDropdownProps> = ({
    initialRange,
    onChanged,
  }) => {
    const [visible, setVisible] = useState(false);
    const [inputTitle, setInputTitle] = useState<string>('');
    const [defaultValue,setDefaultValue] =useState(() => {
        const end = new Date();
        const start = new Date(end.getTime() - 60 * 60 * 1000); // 减1小时
        return `${moment(start).format("YYYY-MM-DD HH:mm")} ~ ${moment(end).format("YYYY-MM-DD HH:mm")}`;
      });
    const [selectedRange, setSelectedRange] = useState<{ label?:string;start: Date; end: Date } | null>(null);

    useEffect(() => {
        if (initialRange) {
          setInputTitle(`${moment(initialRange.start).format("YYYY-MM-DD HH:mm")} ~ ${moment(initialRange.end).format("YYYY-MM-DD HH:mm")}`);
          setSelectedRange(initialRange)
        }
      }, [initialRange]);
      
    // 格式化选中的时间段
    const formatRange = (range: TimeRangeDropdownValueType | null) => {
      if (!range) return "";
      const value =`${moment(range.start).format("YYYY-MM-DD HH:mm")} ~ ${moment(range.end).format("YYYY-MM-DD HH:mm")}`;
      if (range.label){
        
        return range.label;
      }
      return value;
    };
  
    const handleApply = (range:TimeRangeDropdownValueType) => {
      setSelectedRange(range);
      // console.info("select times:"+JSON.stringify(range))
      if (range){
        setInputTitle(`${moment(range.start).format("YYYY-MM-DD HH:mm")} ~ ${moment(range.end).format("YYYY-MM-DD HH:mm")}`);
      }
      setVisible(false); // 关闭弹窗
      //todo:
      onChanged(range);
    };
  
    return (
      <Popover
        content={
          <TimeRangeSelector
            initialRange={
              selectedRange
                ? {
                    label: selectedRange.label,
                    value: [
                      moment(selectedRange.start),
                      moment(selectedRange.end),
                    ],
                  }
                : undefined
            }
            onChanged={handleApply}
          />
        }
        trigger="click"
        open={visible}
        onOpenChange={(v) => setVisible(v)}
        placement="bottomLeft"
      >
        <Tooltip
          title={inputTitle}
          placement="topLeft"
          overlayStyle={{
            maxWidth: "none", // 取消默认最大宽度限制
            whiteSpace: "nowrap", // 禁止换行
          }}
        >
          <Input
            readOnly
            value={formatRange(selectedRange)}
            placeholder={defaultValue}
            onClick={() => setVisible(true)}
            style={{ width: 300, cursor: "pointer" }}
          />
        </Tooltip>
      </Popover>
    );
  };
  
  export default TimeRangeDropdown;
